package com.egene.tw.activity.signs.measure;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.egene.tw.R;
import com.egene.tw.activity.settings.devicelist.DeviceListActivity;
import com.egene.tw.activity.settings.devicelist.DeviceListActivity_;
import com.egene.tw.activity.signs.BaseMeasureActivity;
import com.egene.tw.activity.signs.blood.BloodActivity_;
import com.egene.tw.activity.signs.fatigue.FatigueActivity_;
import com.egene.tw.activity.signs.heart.HeartActivity_;
import com.egene.tw.activity.signs.oxygen.OxygenActivity_;
import com.egene.tw.activity.signs.sleep.SleepActivity_;
import com.egene.tw.activity.signs.step.StepActivity_;
import com.egene.tw.base.BaseFragment;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.bus.BusHelper;
import com.egene.tw.bus.DropDownEvent;
import com.egene.tw.bus.LoadDataEndEvent;
import com.egene.tw.data.DataRepository;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.entity.BloodData;
import com.egene.tw.data.entity.FatigueData;
import com.egene.tw.data.entity.HeartData;
import com.egene.tw.data.entity.OxygenData;
import com.egene.tw.data.entity.SleepData;
import com.egene.tw.data.entity.StepData;
import com.egene.tw.data.utils.CalUtils;
import com.egene.tw.data.wrapper.HomeData;

import org.greenrobot.eventbus.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

@EFragment(R.layout.activity_measure_data)
public class MeasureFragment extends BaseFragment {
    public MeasureFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusHelper.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusHelper.unRegister(this);
    }

    @ViewById(R.id.viewRefresh)
    SwipeRefreshLayout viewRefresh;
    @ViewById(R.id.btnStart)
    TextView btnStart;

    //步数
    @ViewById(R.id.textStep)
    TextView textStep;
    @ViewById(R.id.textStepDate)
    TextView textStepDate;

    //睡眠
    @ViewById(R.id.textSleepHour)
    TextView textSleepHour;
    @ViewById(R.id.textSleepMin)
    TextView textSleepMin;
    @ViewById(R.id.textSleepDate)
    TextView textSleepDate;

    //心率
    @ViewById(R.id.textHeart)
    TextView textHeart;
    @ViewById(R.id.textHeartDate)
    TextView textHeartDate;

    //血压
    @ViewById(R.id.textBloodHigh)
    TextView textBloodHigh;
    @ViewById(R.id.textBloodLow)
    TextView textBloodLow;
    @ViewById(R.id.textBloodDate)
    TextView textBloodDate;

    //血氧
    @ViewById(R.id.textOxygen)
    TextView textOxygen;
    @ViewById(R.id.textOxygenDate)
    TextView textOxygenDate;

    //疲劳
    @ViewById(R.id.textFatigue)
    TextView textFatigue;
    @ViewById(R.id.textFatigueDate)
    TextView textFatigueDate;


    @ViewById(R.id.viewPStep)
    View viewPStep;
    @ViewById(R.id.viewPSleep)
    View viewPSleep;
    @ViewById(R.id.viewPBlood)
    View viewPBlood;
    @ViewById(R.id.viewPOxygen)
    View viewPOxygen;
    @ViewById(R.id.viewPFatigue)
    View viewPFatigue;
    @ViewById(R.id.viewPHeart)
    View viewPHeart;

    @AfterViews
    void initViews() {
        viewRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        String address = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(address)) {
            new AlertDialog.Builder(getActivity())
                    .setTitle("提示")
                    .setMessage("暫未綁定手環，請綁定")
                    .setPositiveButton("前往綁定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(getActivity(), DeviceListActivity_.class));
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();


        viewRefresh.post(new Runnable() {
            @Override
            public void run() {
                viewRefresh.setRefreshing(BluetoothLeServiceV2.isDropDownRefresh && BluetoothLeServiceV2.connected);
            }
        });
    }

    @Click(R.id.viewStep)
    void clickStep() {
        Intent intent = new Intent(getActivity(), StepActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewFatigue)
    void clickFatigue() {
        Intent intent = new Intent(getActivity(), FatigueActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewSleep)
    void clickSleep() {
        Intent intent = new Intent(getActivity(), SleepActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewHeart)
    void viewHeart() {
        Intent intent = new Intent(getActivity(), HeartActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewblood)
    void viewblood() {
        Intent intent = new Intent(getActivity(), BloodActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewOxygen)
    void viewOxygen() {
        Intent intent = new Intent(getActivity(), OxygenActivity_.class);
        startActivity(intent);
    }


    @Subscribe
    public void onEvent(LoadDataEndEvent data) {
        if (viewRefresh == null) {
            return;
        }
        viewRefresh.post(new Runnable() {
            @Override
            public void run() {
                viewRefresh.setRefreshing(BluetoothLeServiceV2.isDropDownRefresh && BluetoothLeServiceV2.connected);
            }
        });
        getData();
    }


    @Subscribe
    public void onEvent(DropDownEvent data) {
        if (viewRefresh == null) {
            return;
        }
        viewRefresh.post(new Runnable() {
            @Override
            public void run() {
                viewRefresh.setRefreshing(BluetoothLeServiceV2.isDropDownRefresh && BluetoothLeServiceV2.connected);
            }
        });
    }


    private void getData() {
        DataRepository.getInstance()
                .homeData()
                .subscribe(new Observer<HomeData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HomeData homeData) {
                        updateUI(homeData);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void refresh() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(getActivity(), R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            viewRefresh.setRefreshing(false);
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(getActivity(), R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            viewRefresh.setRefreshing(false);
            return;
        }
        viewRefresh.setRefreshing(true);
        Activity activity = getActivity();
        if (activity instanceof BaseMeasureActivity) {
            ((BaseMeasureActivity) activity).measureDropDown();
        }
//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                viewRefresh.setRefreshing(false);
//            }
//        }, 3000);

    }


    private void updateUI(HomeData data) {
        StepData stepData = data.getStepData();
        SleepData sleepData = data.getSleepData();
        HeartData heartData = data.getHeartData();
        OxygenData oxygenData = data.getOxygenData();
        BloodData bloodData = data.getBloodData();
        FatigueData fatigueData = data.getFatigueData();


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        //
        textStep.setText(stepData.getValue() == 0 ? "--" : String.valueOf(stepData.getValue()));
        if (stepData.getDetailTime() != 0) {
            textStepDate.setText(sdf.format(stepData.getDetailTime()));
        } else {
            textStepDate.setText("--");
        }
        viewPStep.setVisibility(stepData.getValue() == 0 ? View.GONE : View.VISIBLE);

        //
        textSleepHour.setText(sleepData.getTotal() == 0 ? "--" : String.valueOf(sleepData.getTotal() / 60));
        textSleepMin.setText(sleepData.getTotal() == 0 ? "--" : String.valueOf(sleepData.getTotal() % 60));
        if (sleepData.getTime() != 0) {
            textSleepDate.setText(sdf1.format(sleepData.getTime()));
        } else {
            textSleepDate.setText("--");
        }
        viewPSleep.setVisibility(sleepData.getTotal() == 0 ? View.GONE : View.VISIBLE);

        //
        textHeart.setText(heartData.getValue() == 0 ? "--" : String.valueOf(heartData.getValue()));
        if (heartData.getTime() != 0) {
            textHeartDate.setText(sdf.format(heartData.getTime()));
        } else {
            textHeartDate.setText("--");
        }
        viewPHeart.setVisibility(heartData.getValue() == 0 ? View.GONE : View.VISIBLE);

        //
        textOxygen.setText(oxygenData.getValue() == 0 ? "--" : String.valueOf(oxygenData.getValue()));
        if (oxygenData.getTime() != 0) {
            textOxygenDate.setText(sdf.format(oxygenData.getTime()));
        } else {
            textOxygenDate.setText("--");
        }
        viewPOxygen.setVisibility(oxygenData.getValue() == 0 ? View.GONE : View.VISIBLE);

        //
        textBloodHigh.setText(bloodData.getHighValue() == 0 ? "--" : String.valueOf(bloodData.getHighValue()));
        textBloodLow.setText(bloodData.getLowValue() == 0 ? "--" : String.valueOf(bloodData.getLowValue()));
        if (bloodData.getTime() != 0) {
            textBloodDate.setText(sdf.format(bloodData.getTime()));
        } else {
            textBloodDate.setText("--");
        }
        viewPBlood.setVisibility(bloodData.getHighValue() == 0 ? View.GONE : View.VISIBLE);

        //
        textFatigue.setText(fatigueData.getValue() == 0 ? "--" : CalUtils.getFatigueDesc(fatigueData.getValue()));
        viewPFatigue.setVisibility(fatigueData.getValue() == 0 ? View.GONE : View.VISIBLE);
        if (fatigueData.getTime() != 0) {
            textFatigueDate.setText(sdf.format(fatigueData.getTime()));
        } else {
            textFatigueDate.setText("--");
        }
    }
}
